const Router = require('koa-router')
const axios = require('axios')
const auth = require('../middleware/auth')
const { AISQLLog, ChatHistory, sequelize } = require('../models')
const { Op } = require('sequelize')

const router = new Router({ prefix: '/api/deepseek' })

// DeepSeek API 集成函数
const DEEPSEEK_BASE_URL = 'https://api.deepseek.com'

// 查询余额和总用量
async function getBillingUsage(apiKey) {
  try {
    const key = 'sk-0b620cb2a4014b0a97c80ed6f2e98928'
    const response = await axios.get(`${DEEPSEEK_BASE_URL}/v1/users/me`, {
      headers: {
        'Authorization': `Bearer ${key}`
      }
    })
    return response.data
  } catch (error) {
    console.error('查询DeepSeek用量失败:', error.response?.data || error.message)
    throw error
  }
}

// 查询详细使用记录
async function getUsageDetails(startDate, endDate, apiKey) {
  try {
    const key = 'sk-0b620cb2a4014b0a97c80ed6f2e98928'
    const response = await axios.get(`https://api.deepseek.com/v1/users/me`, {
      headers: {
        Authorization: `Bearer ${key}`
      }
    })
    console.log('DeepSeek用量数据:', response.data)
    return response.data
  } catch (error) {
    console.error('查询DeepSeek详细记录失败:', error.response?.data || error.message)
    throw error
  }
}

router.get('/stats-full',auth.checkPermission('chat:read'), async (ctx) => {
  try {
    const { days = 30 } = ctx.query
    console.log(`获取DeepSeek ${days}天统计数据`)
    
    // 计算日期范围
    const endDate = new Date()
    const startDate = new Date()
    startDate.setDate(endDate.getDate() - parseInt(days))
    
    // 尝试获取真实的DeepSeek使用数据
    let realUsageData = null
    try {
      if (process.env.DEEPSEEK_API_KEY || 'sk-0b620cb2a4014b0a97c80ed6f2e98928') {
        realUsageData = await getBillingUsage()
        console.log('成功获取DeepSeek真实使用数据:', realUsageData)
      } else {
        console.log(' 未配置DEEPSEEK_API_KEY，使用本地统计')
      }
    } catch (apiError) {
      console.log(' 无法获取DeepSeek真实数据，使用本地统计:', apiError.message)
    }
    
    // 从AI SQL日志获取统计数据
    const sqlStats = await AISQLLog.findAll({
      where: {
        created_at: {
          [Op.gte]: startDate,
          [Op.lte]: endDate
        }
      },
      attributes: [
        [sequelize.fn('DATE', sequelize.col('created_at')), 'date'],
        [sequelize.fn('COUNT', sequelize.col('id')), 'sql_count'],
        [sequelize.fn('AVG', sequelize.col('execution_time')), 'avg_execution_time'],
        [sequelize.fn('COUNT', sequelize.literal('CASE WHEN execution_status = "success" THEN 1 END')), 'success_count'],
        [sequelize.fn('COUNT', sequelize.literal('CASE WHEN execution_status = "failed" THEN 1 END')), 'failed_count']
      ],
      group: [sequelize.fn('DATE', sequelize.col('created_at'))],
      order: [[sequelize.fn('DATE', sequelize.col('created_at')), 'ASC']],
      raw: true
    })
    
    // 从聊天历史获取对话统计
    const chatStats = await ChatHistory.findAll({
      where: {
        created_at: {
          [Op.gte]: startDate,
          [Op.lte]: endDate
        }
      },
      attributes: [
        [sequelize.fn('DATE', sequelize.col('created_at')), 'date'],
        [sequelize.fn('COUNT', sequelize.col('id')), 'message_count'],
        [sequelize.fn('SUM', sequelize.col('token_usage')), 'total_tokens'],
        [sequelize.fn('COUNT', sequelize.fn('DISTINCT', sequelize.col('session_id'))), 'session_count']
      ],
      group: [sequelize.fn('DATE', sequelize.col('created_at'))],
      order: [[sequelize.fn('DATE', sequelize.col('created_at')), 'ASC']],
      raw: true
    })
    
    // 合并统计数据
    const statsMap = new Map()
    
    // 处理SQL统计
    sqlStats.forEach(stat => {
      const date = stat.date
      if (!statsMap.has(date)) {
        statsMap.set(date, {
          date,
          sql_count: 0,
          avg_execution_time: 0,
          success_count: 0,
          failed_count: 0,
          message_count: 0,
          total_tokens: 0,
          session_count: 0
        })
      }
      const dayStats = statsMap.get(date)
      dayStats.sql_count = parseInt(stat.sql_count) || 0
      dayStats.avg_execution_time = parseFloat(stat.avg_execution_time) || 0
      dayStats.success_count = parseInt(stat.success_count) || 0
      dayStats.failed_count = parseInt(stat.failed_count) || 0
    })
    
    // 处理聊天统计
    chatStats.forEach(stat => {
      const date = stat.date
      if (!statsMap.has(date)) {
        statsMap.set(date, {
          date,
          sql_count: 0,
          avg_execution_time: 0,
          success_count: 0,
          failed_count: 0,
          message_count: 0,
          total_tokens: 0,
          session_count: 0
        })
      }
      const dayStats = statsMap.get(date)
      dayStats.message_count = parseInt(stat.message_count) || 0
      dayStats.total_tokens = parseInt(stat.total_tokens) || 0
      dayStats.session_count = parseInt(stat.session_count) || 0
    })
    
    // 转换为数组并计算总计
    const dailyStats = Array.from(statsMap.values()).sort((a, b) => new Date(a.date) - new Date(b.date))
    
    // 整合本地统计和真实DeepSeek数据
    const localTokens = dailyStats.reduce((sum, stat) => sum + stat.total_tokens, 0)
    const realTokens = realUsageData ? (realUsageData.total_usage || 0) : 0
    
    const totalStats = {
      total_sessions: dailyStats.reduce((sum, stat) => sum + stat.session_count, 0),
      total_messages: dailyStats.reduce((sum, stat) => sum + stat.message_count, 0),
      total_tokens: realTokens > 0 ? realTokens : localTokens, // 优先使用真实数据
      total_sql_queries: dailyStats.reduce((sum, stat) => sum + stat.sql_count, 0),
      success_rate: dailyStats.length > 0 ? 
        (dailyStats.reduce((sum, stat) => sum + stat.success_count, 0) / 
         Math.max(1, dailyStats.reduce((sum, stat) => sum + stat.sql_count, 0)) * 100) : 0,
      avg_execution_time: dailyStats.length > 0 ? 
        dailyStats.reduce((sum, stat) => sum + stat.avg_execution_time, 0) / dailyStats.length : 0,
      estimated_cost: realUsageData ? realUsageData.total_usage : (localTokens * 0.000014)
    }
    
    ctx.body = {
      success: true,
      data: {
        total_stats: totalStats,
        daily_stats: dailyStats,
        date_range: {
          start_date: startDate.toISOString(),
          end_date: endDate.toISOString(),
          days: parseInt(days)
        },
        // 添加真实DeepSeek账户信息
        deepseek_account: realUsageData ? {
          balance: realUsageData.balance,
          total_usage: realUsageData.total_usage,
          total_granted: realUsageData.total_granted,
          is_real_data: true
        } : {
          message: '无法获取真实账户数据，显示本地估算',
          is_real_data: false
        }
      },
      message: realUsageData ? 'DeepSeek真实使用数据获取成功' : 'DeepSeek本地统计数据获取成功'
    }
    
  } catch (error) {
    console.error('获取DeepSeek统计失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '获取DeepSeek统计数据失败',
      error: error.message
    }
  }
})

// 获取DeepSeek模型信息
router.get('/model-info', auth.checkPermission('chat:read'), async (ctx) => {
  try {
    // DeepSeek配置信息
    const modelInfo = {
      model_name: 'deepseek-chat',
      api_endpoint: 'https://api.deepseek.com/v1/chat/completions',
      max_tokens: 32768,
      temperature: 0.7,
      status: 'active',
      version: '2024.1',
      capabilities: [
        'text-generation',
        'code-generation', 
        'data-analysis',
        'sql-generation',
        'multilingual-support'
      ],
      pricing: {
        input_tokens: 0.00000014, // 每token价格
        output_tokens: 0.00000028,
        currency: 'USD'
      },
      limits: {
        requests_per_minute: 60,
        tokens_per_minute: 600000,
        max_context_length: 32768
      }
    }
    
    // 获取最近的API调用状态
    const recentCalls = await AISQLLog.findAll({
      where: {
        ai_model: 'deepseek-chat',
        created_at: {
          [Op.gte]: new Date(Date.now() - 24 * 60 * 60 * 1000) // 最近24小时
        }
      },
      attributes: [
        'execution_status',
        'execution_time',
        'created_at',
        'error_message'
      ],
      order: [['created_at', 'DESC']],
      limit: 10,
      raw: true
    })
    
    const apiHealth = {
      status: recentCalls.length > 0 && recentCalls[0].execution_status === 'success' ? 'healthy' : 'unknown',
      last_call: recentCalls.length > 0 ? recentCalls[0].created_at : null,
      recent_errors: recentCalls.filter(call => call.execution_status === 'failed').length,
      avg_response_time: recentCalls.length > 0 ? 
        recentCalls.reduce((sum, call) => sum + (call.execution_time || 0), 0) / recentCalls.length : 0
    }
    
    ctx.body = {
      success: true,
      data: {
        model_info: modelInfo,
        api_health: apiHealth,
        recent_calls: recentCalls
      },
      message: '模型信息获取成功'
    }
    
  } catch (error) {
    console.error('获取模型信息失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '获取模型信息失败',
      error: error.message
    }
  }
})

// 获取详细使用记录
router.get('/usage-details', auth.checkPermission('chat:read'), async (ctx) => {
  try {
    const { start_date, end_date } = ctx.query
    
    if (!start_date || !end_date) {
      ctx.status = 400
      ctx.body = {
        success: false,
        message: '请提供start_date和end_date参数'
      }
      return
    }
    
    try {
      const usageDetails = await getUsageDetails(start_date, end_date)
      
      ctx.body = {
        success: true,
        data: usageDetails,
        message: 'DeepSeek详细使用记录获取成功'
      }
    } catch (apiError) {
      ctx.body = {
        success: false,
        message: '无法获取DeepSeek详细使用记录',
        error: apiError.message,
        fallback_message: '请检查DEEPSEEK_API_KEY配置'
      }
    }
    
  } catch (error) {
    console.error('获取详细使用记录失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '获取详细使用记录失败',
      error: error.message
    }
  }
})

module.exports = router
